﻿using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Enums;
using Microsoft.Extensions.Configuration;

namespace DiffuseEnjoyIdle.Core.Extensions
{
    public static class ApolloConfigurationExtensions
    {
        public static IApolloConfigurationBuilder AddApolloExtension(this IConfigurationBuilder builder)
        {
            ApolloOptions apolloOptions = builder.Build().GetSection("apollo").Get<ApolloOptions>();
            if (apolloOptions == null)
            {
                throw new ArgumentNullException("apolloOptions");
            }

            string value = builder.Build()["ApolloEnv"];
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("env");
            }

            Enum.TryParse(value, ignoreCase: true, out Env result);
            apolloOptions.Env = result;

            return builder.AddEnvironmentVariables().AddApollo(apolloOptions).AddDefault(ConfigFileFormat.Json);
        }

        public static IApolloConfigurationBuilder AddApolloExtension(this IConfigurationBuilder builder, string @namespace, ConfigFileFormat configFileFormat = ConfigFileFormat.Json)
        {
            return builder.AddApolloExtension().AddNamespace(@namespace, configFileFormat);
        }

        public static IApolloConfigurationBuilder AddApolloExtension(this IConfigurationBuilder builder, IDictionary<string, ConfigFileFormat> nameSpaceDic)
        {
            IApolloConfigurationBuilder apolloConfigurationBuilder = builder.AddApolloExtension();
            foreach (KeyValuePair<string, ConfigFileFormat> item in nameSpaceDic)
            {
                item.Deconstruct(out string key, out ConfigFileFormat value);
                string @namespace = key;
                ConfigFileFormat format = value;
                apolloConfigurationBuilder.AddNamespace(@namespace, format);
            }

            return apolloConfigurationBuilder;
        }

    }
}
